package project.dwd.wit.ie.tripfinancemanager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;


public class NewExpenseActivity extends ActionBarActivity {

    private EditText date;
    private EditText description;
    private EditText value;

    private String tripName = "";
    private String filename = "";

    private String[] costsTrip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_expense);

        date = (EditText) findViewById(R.id.date_edittext);
        description = (EditText) findViewById(R.id.description_edittext);
        value = (EditText) findViewById(R.id.value_edittext);

        //Getting data from previous Activity...
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            filename = extras.getString("filename");
            tripName = extras.getString("tripName");
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_new_expense, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public void saveNewExpense(View view) {
        String newExpense = date.getText().toString() + "|" +
                            description.getText().toString() + "|" +
                            value.getText().toString();

        Log.e("new Expense", newExpense);
        readAndWriteFile(filename, newExpense);
        finish();
    }

    public void readAndWriteFile(String filename, String newExpense) {
        new ReadFile(this).execute(filename, newExpense);
    }


    private class ReadFile extends AsyncTask<String, Void, String[]> {

        private Activity activity;
        private ProgressDialog dialog;

        public ReadFile(Activity activity) {
            this.activity = activity;
            dialog = new ProgressDialog(activity);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            this.dialog.setMessage("Loading file... please wait");
            this.dialog.show();
            Log.e("onPre", "onPreExecute Method called");
        }

        @Override
        protected String[] doInBackground(String... params) {
            return readFile(params[0], params[1]);
        }

        public String[] readFile(String filename, String newExpense) {
            String tripName = "";
            //Get the text file
            File file = new File(getCacheDir(),filename);
            //Read text from file
            StringBuilder text = new StringBuilder();
            String expenses = "";

            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                //First Line is a Trip Name
                tripName = br.readLine();

                while ((line = br.readLine()) != null) {
                    expenses = expenses + line + "--";
                }
                expenses = expenses + newExpense;

                costsTrip = expenses.split("--");
                br.close();
            }
            catch (IOException e) {
                //You'll need to add proper error handling here
            }

            reCreateFile(filename, tripName, costsTrip);

            return costsTrip;
        }

        public void reCreateFile(String filename, String tripName, String[] costsTrip) {
            String _tripName = tripName;
            Log.e("recreating file... ", _tripName + "!!" + filename);

            File file = new File(getCacheDir() + "/" + filename.toLowerCase());
            Writer out = null;
            if (file.exists()) {
                file.delete();
            }
            try {
                out = new BufferedWriter(new FileWriter(file));
                out.write(_tripName + "\n");

                String sequence = "";
                for (String s : costsTrip) {
                    sequence = sequence + s + "\n";
                }
                out.write(sequence);
                out.flush();
                out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        @Override
        protected void onPostExecute(String[] result) {
            super.onPostExecute(result);

            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

}
